import { reqLogin, reqUserInfo } from "../../api/login";
import { userStore } from "../../stores/userstore";
import { ComponentWithStore } from "mobx-miniprogram-bindings";

ComponentWithStore({
  // 让页面和Store对象建立关联
  storeBindings: {
    store: userStore,
    fields: ["token", "userInfo"],
    actions: ["setToken", "setUserInfo"],
  },

  methods: {
    login() {
      const _this = this;
      wx.login({
        async success(res) {
          if (res) {
            //1,发起网络请求
            const { data } = await reqLogin(res.code);
            // 2，存储到stroe
            wx.setStorageSync("token", data.data.token);

            //  3,将自定义登录 token 存储到 Stroe 对象
            _this.setToken(data.data.token);
            _this.getUserInfo();
            wx.navigateBack();
          } else {
            wx.showToast({ title: "授权失败，请重新授权" });
          }
        },
      });
    },

    async getUserInfo() {
      const { data } = await reqUserInfo();
      wx.setStorageSync("userInfo", data.data);
      this.setUserInfo(data.data);
    },
  },
});
